<?php
/**
 *  +----------------------------------------------------------------------
 *  | CRMEB [ CRMEB赋能开发者，助力企业发展 ]
 *  +----------------------------------------------------------------------
 *  | Copyright (c) 2016~2025 https://www.crmeb.com All rights reserved.
 *  +----------------------------------------------------------------------
 *  | Licensed CRMEB并不是自由软件，未经许可不能去掉CRMEB相关版权
 *  +----------------------------------------------------------------------
 *  | Author: CRMEB Team <admin@crmeb.com>
 *  +----------------------------------------------------------------------
 */

/**
 * 帖子
 * @author crud自动生成代码
 * @date 2025/07/11 22:10:24
 */

namespace app\services\crud;

use app\services\BaseServices;
use think\exception\ValidateException;
use app\dao\crud\PostsDao;
use crmeb\services\FormBuilder;

/**
 * Class CrudService
 * @date 2025/07/11
 * @package app\services\crud
 */
class PostsServices extends BaseServices
{

    /**
     * PostsServices constructor.
     * @param PostsDao $dao
     */
    public function __construct(PostsDao $dao)
    {
        $this->dao = $dao;
    }

    /**
     * 主页数据接口
     * @param array $where
     * @return array
     * @date 2025/07/11
     */
    public function getCrudListIndex(array $where = [])
    {
        [$page, $limit] = $this->getPageValue();

        $model = $this->dao->searchCrudModel($where, 'add_time,price,phone,title,content,user_id,like_count,comment_count,`status` as status_label,id,status,browse', 'id desc', ['userIdHasOne']);

        $list = $model->page($page ?: 1, $limit ?: 10)->select()->toArray();
        /** @var PostLikeServices $postLikeServices */
        $postLikeServices = app()->make(PostLikeServices::class);
        foreach ($list as &$item) {
            $item['add_time_text'] = date('Y-m-d h:i:s',$item['add_time']);
            $is_like = $postLikeServices->getOne(['user_id' => $where['user_id'], 'post_id' => $item['id']]);
            $item['is_like'] = isset($is_like);
        }
        return ['count' => $model->count(), 'list' => $list];
    }

    /**
     * 编辑和获取表单
     * @date 2025/07/11
     * @param int $id
     * @return array
     */
    public function getCrudForm(int $id = 0)
    {
        $url = '/crud/posts';
        $info = [];
        if ($id) {
            $info = $this->dao->get($id);
            if (!$info) {
                throw new ValidateException(100026);
            }
            $url .= '/' . $id;
        }
        $rule = [];

        $rule[] = FormBuilder::input("title", "标题",  $info["title"] ?? '');
        $rule[] = FormBuilder::textarea("content", "内容",  $info["content"] ?? '');
        $rule[] = FormBuilder::input("user_id", "发帖人",  $info["user_id"] ?? '');
        $rule[] = FormBuilder::number("like", "点赞",  $info["like"] ?? '');
        $rule[] = FormBuilder::number("viewers", "观看人数",  $info["viewers"] ?? '');
        $rule[] = FormBuilder::number("forward", "转发数",  $info["forward"] ?? '');
        $rule[] = FormBuilder::number("universi_type_id", "帖子分类",  $info["universi_type_id"] ?? '');

        if (isset($info['images'])) {
            $pics = is_array($info['images']) ? $info['images'] : json_decode($info['images'], true);
        } else {
            $pics = [];
        }
        $pics = is_array($pics) ? $pics : [];
        $rule[] = FormBuilder::frameImages('images', '图片', url(config('app.admin_prefix', 'admin') . '/widget.images/index', ['fodder' => 'images', 'type' => 'many', 'maxLength' => 10]), $pics)->maxLength(10)->icon('el-icon-picture-outline')->width('950px')->height('560px')->Props(['footer' => false])->required();
        $rule[] = FormBuilder::select("status", "帖子状态",  isset($info['status']) ? (int)$info['status'] : '')->options([
            ['value'=>0, 'label'=>'待审核'],
            ['value'=>1, 'label'=>'已审核'],
            ['value'=>2, 'label'=>'封禁'],
            ['value'=>3, 'label'=>'锁定'],
        ]);

        return create_form('帖子', $rule, $url, $id ? 'PUT' : 'POST');
    }

    /**
     * 新增
     * @date 2025/07/11
     * @param array $data
     * @return mixed
     */
    public function crudSave(array $data)
    {
        return $this->dao->save($data);
    }

    /**
     * 修改
     * @date 2025/07/11
     * @param int $id
     * @param array $data
     * @return \crmeb\basic\BaseModel
     */
    public function crudUpdate(int $id, array $data)
    {
        return $this->dao->update($id, $data);
    }

    public function details($id)
    {
        try {
            $post = $this->dao->searchCrudModel(['id' => $id], 'add_time,phone,price,title,content,user_id,like_count,comment_count,`status` as status_label,id,status,browse,vote_start_time,vote_end_time,total_votes', 'id desc', ['userIdHasOne'])->find();
            // 浏览量增加
            $this->dao->update($id, ['browse' => $post['browse'] + 1]);
            return compact('post');
        }catch (\Exception $e) {
            return [];
        }
    }


}
